package com.banzhi.shop.activity;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.banzhi.shop.MyApp;
import com.banzhi.shop.R;
import com.banzhi.shop.base.BaseActivity;
import com.banzhi.shop.data.GroupPayBean;
import com.banzhi.shop.demo.PayResult;
import com.banzhi.shop.entity.Checkstand.WXPay_Data;

import com.banzhi.shop.model.CallBack.CheckStandCallBack2;
import com.banzhi.shop.model.CallBack.GroupPayCallback;
import com.banzhi.shop.model.Impl.GroupPayImpl;
import com.banzhi.shop.model.Impl.GroupPayImpl2;
import com.banzhi.shop.utils.LoadingDialogUtils;
import com.banzhi.shop.utils.LogUtils;
import com.banzhi.shop.utils.NoTokenUtils;
import com.banzhi.shop.utils.ToastUtils;
import com.banzhi.shop.utils.Translucent;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONObject;

import java.util.Map;

import static com.banzhi.shop.MyApp.APP_ID;

//收银台(拼团支付)
public class CheckstandGroupActivity extends BaseActivity implements View.OnClickListener, CheckStandCallBack2, Handler.Callback, GroupPayCallback {
    private static final int SDK_PAY_FLAG = 0;
    private ImageView mIvBack;
    private TextView mTvBianma;
    private TextView mTvPrice;
    private TextView mTvYuE;
    private LinearLayout mLinearLayout;
    private LinearLayout mWinXingZhiFu;
    private LinearLayout mZhifubao;
    private LinearLayout mLlPayYuE;
    private String mOrderno;
    private String mPrice;
    private String mBalance;
    private GroupPayImpl mModel;
    private GroupPayImpl2 mModel2;
    /**
     * 微信支付实体类
     */
    private WXPay_Data pay;
    private Handler handler;
    private GroupPayBean mPayBean;
    private String mGoodid;
   // private String mTeamid;
    private String mType;
    private Receiver mReceiver;
    private String teamid;
    private String mOrdersn;
    private String mTt;
    private String flag;
    private String mTeamid;

    /**
     * 注册广播接受者
     */

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_checkstand_group);
        Translucent.setTranslucent(this);
        initView();
        setListener();

        Intent intent = getIntent();
        mOrderno = intent.getStringExtra("orderno");
        mPrice = intent.getStringExtra("price");
        mBalance = intent.getStringExtra("balance");
        mOrdersn = intent.getStringExtra("bianma");
        flag = intent.getStringExtra("flag");
        mTeamid = intent.getStringExtra("teamid");
        mTt = intent.getStringExtra("TT");
             SharedPreferences.Editor editor = MyApp.loginMessage.edit();

        if (!mTt.equals("")) {
            editor.putString("mTt", mTt);
        }
        if ("3".equals(flag)) {
            editor.putString("flag", "3");
        }
        editor.apply();
        showView();
        mModel = new GroupPayImpl();
        mModel2 = new GroupPayImpl2();
        if ("1".equals( mTt)) {
            mModel.PayYure(mOrdersn, "credit", this);
        }else {
            mModel.PayYure(mOrderno, "credit", this);
        }







        handler = new Handler(this);
        // 注册广播接受者this
        mReceiver = new Receiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.banzhi");
        registerReceiver(mReceiver, filter);


    }


    private void initView() {
        mIvBack = (ImageView) findViewById(R.id.iv_back);
        mTvBianma = (TextView) findViewById(R.id.tv_bianma);
        mTvPrice = (TextView) findViewById(R.id.tv_price);
        mTvYuE = (TextView) findViewById(R.id.tv_yure_group);
        mWinXingZhiFu = (LinearLayout) findViewById(R.id.ll_weixingzhifu);
        mZhifubao = (LinearLayout) findViewById(R.id.ll_zhifubao);
        mLlPayYuE = (LinearLayout) findViewById(R.id.ll_pay_yue);
    }
    private void showView() {

        if ("1".equals(mTt)) {
            mTvBianma.setText(mOrdersn);
        }else {
            mTvBianma.setText(mOrderno);
        }

        mTvPrice.setText(mPrice);

        mTvYuE.setText(mBalance);

    }


    private void setListener() {
        mIvBack.setOnClickListener(this);
        mWinXingZhiFu.setOnClickListener(this);
        mZhifubao.setOnClickListener(this);
        mLlPayYuE.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.ll_weixingzhifu:
                LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");

                if ("1".equals(mTt)) {
                    mModel2.PayWX(mOrdersn, mPrice, this);
                }else {
                    mModel2.PayWX(mOrderno, mPrice, this);
                }
                break;
            case R.id.ll_zhifubao:
                LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
                if ("1".equals(mTt)) {
                    mModel2.PayZFB(mOrdersn, mPrice, this);
                }else {
                    mModel2.PayWX(mOrderno, mPrice, this);
                }


                break;
            case R.id.ll_pay_yue:
                showPopupWindow(view);
                break;
        }

    }

    private void showPopupWindow(View view) {
        View contentView = LayoutInflater.from(CheckstandGroupActivity.this).inflate(R.layout.popumwindow_yu_e, null);
        int width = LinearLayout.LayoutParams.MATCH_PARENT;
        int height = WindowManager.LayoutParams.MATCH_PARENT;
        final PopupWindow popupWindow = new PopupWindow(contentView, width, height);
        popupWindow.setAnimationStyle(R.style.AnimBottom);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(false);//允许在外点击消失
        //设置各个控件 的点击相应
        TextView tvCancle = (TextView) contentView.findViewById(R.id.tv_cancle);
        TextView tvTrue = (TextView) contentView.findViewById(R.id.tv_true);
        tvCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        tvTrue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                LoadingDialogUtils.showProgress(CheckstandGroupActivity.this, "正在加载,请稍后~");



                if ("1".equals(mTt)) {
                    mModel2.PayYure(mOrdersn, mPrice, CheckstandGroupActivity.this);
                }else {
                    mModel2.PayYure(mOrderno, mPrice, CheckstandGroupActivity.this);
                }


                popupWindow.dismiss();
            }
        });

        View rootView = LayoutInflater.from(CheckstandGroupActivity.this).inflate(R.layout.activity_commodity_details, null);
        popupWindow.showAtLocation(rootView, Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);

    }

    //余额支付成功
    @Override
    public void onPayYureSuccess(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
        if ("1".equals(mTt)) {
            showBuySuccessWindow();
        }else {
            Intent intent = new Intent(this, GroupOrderDetailsActivity.class);
            intent.putExtra("goodid",mGoodid);
            if ("3".equals(flag)) {

                intent.putExtra("teamid",mTeamid);
            }else {
                intent.putExtra("teamid",teamid);
            }

            intent.putExtra("type",mType);
            startActivity(intent);
            finish();
        }


    }

    private void showBuySuccessWindow() {
        View contentView = LayoutInflater.from(CheckstandGroupActivity.this).inflate(R.layout.popumwindow_yu_e2, null);
        int width = LinearLayout.LayoutParams.MATCH_PARENT;
        int height = WindowManager.LayoutParams.MATCH_PARENT;
        final PopupWindow popupWindow = new PopupWindow(contentView, width, height);
        popupWindow.setAnimationStyle(R.style.AnimBottom);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(false);//允许在外点击消失
        //设置各个控件 的点击相应

        TextView tvTrue = (TextView) contentView.findViewById(R.id.tv_true);

        tvTrue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(CheckstandGroupActivity.this, BuyOrderActivity.class);
                intent.putExtra("price",mPrice);
                startActivity(intent);

                popupWindow.dismiss();
            }
        });

        View rootView = LayoutInflater.from(CheckstandGroupActivity.this).inflate(R.layout.activity_commodity_details, null);
        popupWindow.showAtLocation(rootView, Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    @Override
    public void onPayYureError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }
    //微信支付
    @Override
    public void onPayWXSuccess(Object object) {
        pay = (WXPay_Data) object;
        WeChatPay(pay);


    }

    private void WeChatPay(WXPay_Data data) {
        if (null == data) {
            //判断是否为空。丢一个toast，给个提示。比如服务器异常，错误啥的
            ToastUtils.makeToastShort("服务器异常");
            return;
        }
        IWXAPI api = WXAPIFactory.createWXAPI(this, APP_ID);
        if (!api.isWXAppInstalled()) {
            ToastUtils.makeToastShort("没有安装微信");
        }
        if (!api.isWXAppSupportAPI()) {
            ToastUtils.makeToastShort("当前版本不支持支付功能");
        }
        //data  根据服务器返回的json数据创建的实体类对象
        PayReq req = new PayReq();
        req.appId = data.getAppid();
        req.partnerId = data.getPartnerid();
        req.prepayId = data.getPrepayid();
        req.packageValue = "Sign=WXPay";
        req.nonceStr = data.getNoncestr();
        req.timeStamp = data.getTimestamp();
        req.sign = data.getSign();
        api.registerApp(APP_ID);
        //发起请求
        api.sendReq(req);

    }

    @Override
    public void onPayWXError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));

    }

    @Override
    public void onPayZFBSuccess(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        final String orderInfo = jsonObject.optString("data");
        LogUtils.e("result","1");
        new Thread() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(CheckstandGroupActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Message msg = new Message();
                msg.what = 2;
                msg.obj = result;
                LogUtils.e("result","2");
                handler.sendMessage(msg);
                LogUtils.e("result","3");

            }
        }.start();

    }

    @Override
    public void onPayZFBError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    @Override
    public boolean handleMessage(final Message msg) {
        ToastUtils.makeToastShort("获取订单中...");
        LogUtils.e("result","4");
        switch (msg.what) {
            case 2:
                PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                String resultInfo = payResult.getResult();
                String resultStatus = payResult.getResultStatus();
                if (TextUtils.equals(resultStatus, "9000")) {
                    ToastUtils.makeToastShort("支付成功");
                    if ("1".equals(mTt)) {
                        showBuySuccessWindow();

                    }else {
                        Intent intent = new Intent(this, GroupOrderDetailsActivity.class);
                        intent.putExtra("goodid",mGoodid);
                        intent.putExtra("teamid",teamid);
                        intent.putExtra("type",mType);

                        startActivity(intent);
                        finish();
                    }

                } else {
                    if (TextUtils.equals(resultStatus, "8000")) {
                        ToastUtils.makeToastShort("支付结果确认中");
                    } else {
                        ToastUtils.makeToastShort("支付失败");
                    }
                }
                break;

        }
        return false;
    }

    //获取goodid 和teamid
    @Override
    public void onPayYueGroupPaySuccess(Object object) {
        mPayBean = (GroupPayBean) object;
        mGoodid = mPayBean.getGoodid();
        teamid = mPayBean.getTeamid();
        mType = mPayBean.getType();
    }

    @Override
    public void onPayYueGroupPayError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    @Override
    public void onPayWXGroupPaySuccess(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    @Override
    public void onPayWXGroupPayError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    @Override
    public void onPayZFBGroupPaySuccess(Object object) {
    }

    @Override
    public void onPayZFBGroupPayError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    public class Receiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if ("com.banzhi".equals(action)) {
                ToastUtils.makeToastShort("支付成功");
                if ("1".equals(mTt)) {
                    showBuySuccessWindow();

                }else {
                    Intent wxintent = new Intent(CheckstandGroupActivity.this, GroupOrderDetailsActivity.class);
                    wxintent.putExtra("goodid",mGoodid);
                    wxintent.putExtra("teamid",teamid);
                    wxintent.putExtra("type",mType);
                    startActivity(intent);
                    finish();
                }

            }
        }
    }

    @Override
    public void onDestroy() {
        // 注销广播接受者
        unregisterReceiver(mReceiver);
        super.onDestroy();
    }
}
